package com.sparrow.common.util;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * 签名工具类
 * 作用：
 * 1验证数据发送者的身份，防止伪造数据。
 * 2保证数据传输完整性，防止被篡改。
 * key 是对称的私钥 双方都要知道这个私钥
 */
public class SignUtil {

    /**
     * 生成签名
     * @param paramStr 参数字符串
     * @param secretKey 秘钥
     * @return
     */
    public static String generateSign(String paramStr, String secretKey) {
        try {
            // 拼接字符串，顺序和格式要固定
            String data = paramStr + secretKey;
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(data.getBytes(StandardCharsets.UTF_8));
            // 转成16进制字符串
            return ByteUtil.toHexString(digest);
        } catch (Exception e) {
            throw new RuntimeException("MD5 algorithm not found");
        }
    }


    public static void main(String[] args) {
        String orderId = "1";
        String account = "a";
        long playerId = 10000000001L;
        int serverId = 1;
        int money = 6;
        String raw = String.format("orderId=%s&account=%s&server=%d&playerId=%d&money=%d",
                orderId, account, serverId, playerId, money);
        String key = "qwer!@#";

        String sign = generateSign(raw, key);
        System.out.println("签名sign = " + sign);
    }
}
